import __config from '../config/env.js'

const request = (url, method, data, showLoading, header) => {
  let _url = __config.basePath + url
  return new Promise((resolve, reject) => {
      if (showLoading) {
        uni.showLoading({
          title: '加载中',
          mask:true
        })
      }
      var head = {
        "Accept": "application/json",
        "Authorization": uni.getStorageSync('token'),
      }
      if (header == 'formData') {
        head = {
          "Content-Type": "application/x-www-form-urlencoded",
          "Accept": "application/json",
          "Authorization": uni.getStorageSync('token')
        }
      }
      uni.request({
        url: _url,
        method: method,
        data: data,
        header: head,
        success(res) {
          if (res.data.code == 200) {
            resolve(res.data)
          } else if (res.data.code == 500) {
            uni.showModal({
              title: '提示',
              content: res.data.msg == '' ? '系统繁忙' : res.data.msg ,
            })
            reject(res.data.msg)

          } else if(res.data.code == 403){
            uni.showModal({
              title: '提示',
              content: res.data.msg == '' ? '系统繁忙' : res.data.msg ,
            })
            reject(res.data.msg)
          } else if (res.data.code == 401) {
            uni.removeStorageSync('token')
            uni.showToast({
              title: "页面过期请重新登陆",
              icon: "none",
              duration: 2000
            })
            setTimeout(function () {
              uni.reLaunch({
                url: "/pages/login/login"
              })
            }, 1000)
            reject()
            return false
          } else {
            uni.showModal({
              title: '提示',
              content: res.data.msg,
            })

            reject()
          }
        },
        fail(error) {
          console.log(error)
          uni.showModal({
            title: '提示',
            content: '接口请求出错：' + error.errMsg,
            success(res) {

            }
          })
          reject(error)
        },
        complete(res) {
          if (showLoading){
            uni.hideLoading()

          }
        }
      })
    }
  )
}
module.exports = {
  request
}
